"""
转换服务模块
"""

import subprocess
from pathlib import Path
from typing import Dict, Any, Optional
from app.config import Config
from app.utils.exceptions import ConversionError


class ConvertService:
    """转换服务类"""
    
    def __init__(self):
        self.config = Config()
        self.supported_formats = {
            'docx': self._convert_to_docx,
            'html': self._convert_to_html,
            'pdf': self._convert_to_pdf
        }
    
    def convert(self, input_file: Path, output_file: Path, 
                target_format: str, options: Dict[str, Any] = None) -> bool:
        """
        统一转换接口
        
        Args:
            input_file: 输入文件路径
            output_file: 输出文件路径
            target_format: 目标格式
            options: 转换选项
            
        Returns:
            bool: 转换是否成功
            
        Raises:
            ConversionError: 转换过程中发生错误
        """
        if target_format not in self.supported_formats:
            raise ConversionError(f"不支持的格式: {target_format}")
        
        converter = self.supported_formats[target_format]
        return converter(input_file, output_file, options or {})
    
    def _convert_to_docx(self, input_file: Path, output_file: Path, 
                        options: Dict[str, Any]) -> bool:
        """转换为Word格式"""
        cmd = [
            self.config.PANDOC_PATH,
            str(input_file),
            "-o", str(output_file),
            "--from", "markdown",
            "--to", "docx"
        ]
        
        # 添加模板选项
        if template := options.get('template'):
            cmd.extend(["--reference-doc", template])
        
        return self._execute_pandoc(cmd)
    
    def _convert_to_html(self, input_file: Path, output_file: Path, 
                        options: Dict[str, Any]) -> bool:
        """转换为HTML格式"""
        cmd = [
            self.config.PANDOC_PATH,
            str(input_file),
            "-o", str(output_file),
            "--from", "markdown",
            "--to", "html5",
            "--standalone",
            "--highlight-style", options.get('highlight_style', 'github')
        ]
        
        # 添加CSS主题
        if css_theme := options.get('css_theme'):
            cmd.extend(["--css", css_theme])
        
        return self._execute_pandoc(cmd)
    
    def _convert_to_pdf(self, input_file: Path, output_file: Path, 
                       options: Dict[str, Any]) -> bool:
        """转换为PDF格式"""
        cmd = [
            self.config.PANDOC_PATH,
            str(input_file),
            "-o", str(output_file),
            "--from", "markdown",
            "--to", "pdf",
            "--pdf-engine", "weasyprint"
        ]
        
        # 添加页面设置
        if page_size := options.get('page_size'):
            cmd.extend(["-V", f"geometry:papersize={page_size}"])
        
        return self._execute_pandoc(cmd)
    
    def _execute_pandoc(self, cmd: list) -> bool:
        """
        执行Pandoc命令
        
        Args:
            cmd: 命令列表
            
        Returns:
            bool: 执行是否成功
            
        Raises:
            ConversionError: 命令执行失败
        """
        try:
            result = subprocess.run(
                cmd,
                timeout=self.config.CONVERSION_TIMEOUT,
                capture_output=True,
                text=True
            )
            
            if result.returncode != 0:
                raise ConversionError(f"Pandoc转换失败: {result.stderr}")
            
            return True
            
        except subprocess.TimeoutExpired:
            raise ConversionError("转换超时")
        except FileNotFoundError:
            raise ConversionError("Pandoc未安装或路径配置错误")